package com.example.statistics.ui.market

import android.os.Bundle
import com.example.statistics.R
import com.example.statistics.bean.MarketBean
import com.example.statistics.bean.PreferenceArea
import com.example.statistics.common.BaseLoadingListActivity
import com.example.statistics.constant.PreferenceConstants
import com.example.statistics.ex.preferenceFind
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.holder.ViewInjector
import org.jetbrains.anko.startActivity

class MarketInfoListActivity : BaseLoadingListActivity<MarketBean>() {

    private var action: String? = ""

    override val title: String
        get() = "市场"

    override val url: String
        get() = UrlConfig.MARKET_LIST

    override val itemLayoutRes: Int
        get() = R.layout.list_item_common_display

    override val httpParams: MutableList<Pair<String, String>>
        get() {
            val city = intent.getStringExtra(Constants.CITY)
            val params = mutableListOf<Pair<String, String>>()
            params.add("city" to city.orEmpty())
            return params
        }


    override val inputSearch: Boolean
        get() = true

    override fun formatList(dataList: MutableList<MarketBean>): MutableList<MarketBean> {
        if (action == Constants.SELECTOR) {
            val list = super.formatList(dataList)
            val marketCity = preferenceFind(PreferenceArea::class.java, PreferenceConstants.MARKET_CITY)
            list.add(
                MarketBean(
                    province = marketCity?.province.orEmpty(),
                    city = marketCity?.city.orEmpty(),
                    area = marketCity?.area.orEmpty(),
                    position = "",
                    market = "其他"
                )
            )
            return list
        }
        return super.formatList(dataList)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        action = intent.getStringExtra(Constants.ACTION)
        topBarRightImage {
            activityForResult<MarketInfoAddActivity>() {
                refresh()
            }
        }
    }

    override fun itemViewConvert(adapter: SlimAdapter, injector: ViewInjector, bean: MarketBean, position: Int) {
        val area = if (bean.area?.endsWith("区") == true)
            bean.city + bean.area
        else
            bean.area
        injector.text(R.id.tv_title, area + bean.market)
            .text(R.id.tv_subtitle, area + bean.position)
            .clicked {
                if (action == Constants.SELECTOR) {
                    activityFinish(Constants.DATA to bean)
                } else {
                    startActivity<MarketCustomerListActivity>(Constants.ID to bean.ID)
                }
            }
    }
}
